package com.uuuo.retrofit2.TypeParse;

import android.util.Log;

import com.google.gson.Gson;
import com.uuuo.retrofit2.Converter.ApiException;
import com.uuuo.retrofit2.Converter.HttpBaseResult;
import com.uuuo.retrofit2.Converter.HttpResult;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by JiaTao on 2018/5/16.
 * Email: 535318720@qq.com
 * Version: 1.0
 * Description:
 */
class GsonResponseBodyConverter<T> implements Converter<ResponseBody, HttpResult<T>> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public HttpResult<T> convert(ResponseBody value) throws IOException {
        String response = value.string();
        try {
            Log.d("Network", "response>>" + response);
            //ResultResponse 只解析result字段
            Type parameterizedType = ((ParameterizedType) type).getActualTypeArguments()[0];

            HttpResult<T>  tHttpResult;
            if (parameterizedType instanceof ParameterizedType) {
                Class classT = (Class) ((ParameterizedType) parameterizedType).getActualTypeArguments()[0];
                tHttpResult = fromJsonArray(response, classT);
            } else {
                tHttpResult = fromJsonObject(response, (Class) parameterizedType);
            }
            return tHttpResult;
        } catch (Exception e) {
            e.printStackTrace();

            //ErrResponse 将msg解析为异常消息文本
            HttpBaseResult errResponse = gson.fromJson(response, HttpBaseResult.class);
            throw new ApiException(errResponse.getErrorCode(), errResponse.getErrorMsg());
        }
    }


    public HttpResult<T> fromJsonObject(String jsonStr, Class clazz) {
        Type type = new ParameterizedTypeImpl(HttpResult.class, new Class[]{clazz});
        return Convert.fromJson(jsonStr, type);
    }


    public HttpResult<T> fromJsonArray(String jsonStr, Class clazz) {
        // 生成List<T> 中的 List<T>
        Type listType = new ParameterizedTypeImpl(List.class, new Class[]{clazz});
        // 根据List<T>生成完整的Result<List<T>>
        Type type = new ParameterizedTypeImpl(HttpResult.class, new Type[]{listType});
        return Convert.fromJson(jsonStr, type);
    }
}